
#ifndef __IWL_SNMP_SERVER_H_3847_
#define __IWL_SNMP_SERVER_H_3847_

#include "RtDebug.h"
#include "RtTimerWrapper.h"
#include "RtTimeValue.h"
#include "RtConfigInitFile.h"
#include "monitorapi.h"

#define IWL_CFG_GROUP_SNMP_MONITOR "SNMP"
#define IWL_CFG_ITEM_SNMP_MONITORINTERVAL "Interval"

template <typename TargetType , typename Snmp_Monitor_Struct_Type>
class SnmpMonitorServer: public CRtTimerWrapperSink
{
public:
	SnmpMonitorServer()
	: m_pTarget(NULL),
	m_bRegisterSuc(FALSE)
	{
	}
	virtual ~SnmpMonitorServer()
	{
		Release();
	}

public:
	RtResult Initialize(TargetType* pTarget ,
						const CRtString& type , 
						const CRtString& Address , 
						const CRtString& Version)
	{
#ifndef SNMP_SUPPORT
		return RT_OK;
#else // SNMP_SUPPORT

		RT_ASSERTE( pTarget != NULL );
		m_pTarget = pTarget;
		/* Initialize SNMP module. */
		RtResult rv = shm_server_register((char*)type.c_str(), TRUE);
		if (RT_FAILED(rv)) 
		{
			RT_ERROR_TRACE("[SnmpMonitorServer] SnmpMonitorServer::Initialize, shm_server_register failed! rv="<<rv);
			return rv;
		}

		m_bRegisterSuc = TRUE;
		memset( &m_MonitorStruct , 0x00 , sizeof(m_MonitorStruct));
		
		strncpy( m_MonitorStruct.gen_info.type , type.c_str() , MAX_SVR_TYPE_LEN -1 );
		strncpy( m_MonitorStruct.gen_info.addresss , Address.c_str() , MAX_IP_ADDR_LEN -1 );
		strncpy( m_MonitorStruct.gen_info.version , Version.c_str() , MAX_SVR_VER_LEN -1 );
		
		m_MonitorStruct.gen_info.start_time = time(NULL);

		/* Get GcMonitor configuration */
		CRtConfigInitFile configInit;
		m_nInterval = configInit.GetWordParam(IWL_CFG_GROUP_SNMP_MONITOR, 
											  IWL_CFG_ITEM_SNMP_MONITORINTERVAL, 
											  5);
		m_monitorTimer.Schedule( this , (float)m_nInterval );
		return RT_OK;
#endif // SNMP_SUPPORT
	}

	void Release()
	{
#ifndef SNMP_SUPPORT
		return;
#else // SNMP_SUPPORT		
		m_pTarget = NULL;
		m_monitorTimer.Cancel();
		if ( m_bRegisterSuc)
		{
			shm_server_unregister();
			m_bRegisterSuc = FALSE;
		}
#endif // SNMP_SUPPORT
	}

protected: // from CRtTimerWrapperSink
	virtual void OnTimer(CRtTimerWrapper* aId)
	{
#ifndef SNMP_SUPPORT
		return ;
#else // SNMP_SUPPORT
		RT_ASSERTE( m_pTarget != NULL );
		m_pTarget->FillSnmpData(&m_MonitorStruct);

		m_MonitorStruct.gen_info.time_stamp = time(NULL);
		m_MonitorStruct.gen_info.status = RT_SERVER_OPEN;
	
		Snmp_Monitor_Struct_Type* pDataStruct = (Snmp_Monitor_Struct_Type*)shm_lock();
		if ( pDataStruct == NULL )
		{
			RT_ERROR_TRACE("[SnmpMonitorServer] Shm Local Failed");
			return;
		}
		
		memcpy( pDataStruct , &m_MonitorStruct , sizeof(m_MonitorStruct));
		shm_unlock();
#endif // SNMP_SUPPORT
	}

protected:
	
	TargetType* m_pTarget;
	bool m_bRegisterSuc;
	
#ifdef SNMP_SUPPORT
	Snmp_Monitor_Struct_Type m_MonitorStruct;
	CRtTimerWrapper m_monitorTimer;
	int m_nInterval;
#endif // SNMP_SUPPORT

};

#endif // __IWL_SNMP_SERVER_H_3847_

